<template>
    <div style="overflow: auto;min-height: calc(100vh - 40px);width: 210mm;margin: 0 auto;background-color: #FFFFFF;padding: 20px;">
        <div class="button-container">
            <el-button type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
            <span>
                <el-button v-if="!isView" @click="addItem" icon="el-icon-plus">新增稽查项目</el-button>
                <el-button v-if="!isView" type="success" icon="el-icon-check" @click="saveData">保存</el-button>
                <el-button v-if="!isView" type="primary" icon="el-icon-menu" @click="goToList">列表</el-button>
                <el-button v-if="!isView" type="danger" icon="el-icon-delete" @click="deleteSelected">删除选中</el-button>
                <el-button @click="printPDF" type="info">打印pdf</el-button>
            </span>
        </div>

        <div id="form">
            <h2>文件/资料稽查表</h2>
            <el-table :data="inspectionList" border style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column v-if="!isView" type="selection" width="55">
                </el-table-column>
                <el-table-column label="序号" type="index" width="50">
                </el-table-column>
                <el-table-column label="稽查时间" width="180">
                    <template slot-scope="scope">
                        <el-date-picker v-if="!isView" v-model="scope.row.inspectionTime" type="datetime"
                            placeholder="选择日期时间" :disabled="isView">
                        </el-date-picker>
                        <!-- 使用 formatDateTime 方法格式化日期 -->
                        <span v-else>{{ formatDateTime(scope.row.inspectionTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="稽查部门" width="180">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.inspectionDepartment" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="主要稽查项目">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.mainInspectionItems" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="稽查状况描述">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.inspectionStatusDescription" type="textarea"
                            :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="责任单位确认">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.responsibleUnitConfirmation" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="备注">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.remarks" :disabled="isView"></el-input>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
import { getInspectionById, saveInspection } from '@/api/inspection'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
// 导入日期格式化方法
import { formatDateTime, DATE_FORMAT } from '@/utils/date'

export default {
    data() {
        return {
            inspectionList: [this.getEmptyRecord()],
            selectedRows: [],
            isView: false,
            isEdit: false,
            id: null
        }
    },
    created() {
        const { id, type } = this.$route.query
        this.id = id
        this.isView = type === 'view'
        this.isEdit = type === 'edit'

        if (id) {
            this.fetchData()
        }
    },
    methods: {
        getEmptyRecord() {
            return {
                inspectionTime: null,
                inspectionDepartment: '',
                mainInspectionItems: '',
                inspectionStatusDescription: '',
                responsibleUnitConfirmation: '',
                remarks: ''
            }
        },
        async fetchData() {
            try {
                const response = await getInspectionById(this.id)
                if (response.data) {
                    // 格式化获取到的数据中的日期
                    response.data.inspectionTime = formatDateTime(response.data.inspectionTime);
                    this.inspectionList = [response.data]
                }
            } catch (error) {
                this.$message.error('获取数据失败')
            }
        },
        validateData() {
            let isValid = true
            this.inspectionList.forEach((item, index) => {
                if (!item.inspectionTime || !item.inspectionDepartment || !item.mainInspectionItems) {
                    this.$message.error(`第${index + 1}行的稽查时间、稽查部门和主要稽查项目为必填项`)
                    isValid = false
                }
            })
            return isValid
        },
        async saveData() {
            if (!this.validateData()) {
                return
            }
            try {
                // 确保保存时日期格式正确
                const formattedList = this.inspectionList.map(item => {
                    return {
                        ...item,
                        inspectionTime: formatDateTime(item.inspectionTime)
                    };
                });
                await saveInspection(formattedList)
                this.$message.success('保存成功')
                this.$router.push('/main/renshi/renshizhidu/jichabiao/jichabiaoList')
            } catch (error) {
                this.$message.error('保存失败')
            }
        },
        goToList() {
            this.$router.push('/main/renshi/renshizhidu/jichabiao/jichabiaoList')
        },
        addItem() {
            this.inspectionList.push(this.getEmptyRecord())
        },
        handleSelectionChange(val) {
            this.selectedRows = val
        },
        deleteSelected() {
            if (this.selectedRows.length === 0) {
                this.$message.warning('请选择要删除的记录')
                return
            }
            const selectedIndices = this.selectedRows.map(row => this.inspectionList.indexOf(row))
            selectedIndices.sort((a, b) => b - a).forEach(index => {
                this.inspectionList.splice(index, 1)
            })
            if (this.inspectionList.length === 0) {
                this.inspectionList.push(this.getEmptyRecord())
            }
        },
        goBack() {
            this.$router.push('/main/renshi/renshizhidu')
        },
        async printPDF() {
            const element = document.querySelector('#form')
            try {
                const canvas = await html2canvas(element)
                const imgData = canvas.toDataURL('image/png')
                const pdf = new jsPDF('p', 'pt', 'a4')
                const imgWidth = 522
                const pageHeight = 841.89
                const imgHeight = (canvas.height * imgWidth) / canvas.width
                let heightLeft = imgHeight
                let position = 0

                pdf.addImage(imgData, 'PNG', 40, position, imgWidth, imgHeight)
                heightLeft -= pageHeight

                while (heightLeft >= 0) {
                    position = heightLeft - imgHeight
                    pdf.addPage()
                    pdf.addImage(imgData, 'PNG', 40, position, imgWidth, imgHeight)
                    heightLeft -= pageHeight
                }
                pdf.save('文件资料稽查表.pdf')
            } catch (error) {
                this.$message.error('生成PDF失败')
            }
        },
        // 将 formatDateTime 方法添加到实例方法中
        formatDateTime
    },
    // 移除原有的过滤器
    // filters: {
    //     parseTime(time) {
    //         return time ? new Date(time).toLocaleString() : ''
    //     }
    // }
}
</script>

<style scoped>
.button-container {
    margin: 20px 0px;
    text-align: right;
    display: flex;
    justify-content: space-between;
}

table {
    border-collapse: collapse;
    width: 100%;
    margin-top: 10px;
}

th,
td {
    border: 1px solid #000;
    padding: 8px;
}

input {
    width: 100%;
    border: none;
    outline: none;
}

input:disabled {
    background-color: #f5f7fa;
    cursor: not-allowed;
}

.el-input--prefix .el-input__inner {
    padding-left: 30px;
    width: 73%;
}

.el-input.is-disabled .el-input__inner {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #606266;
    cursor: not-allowed;
}
</style>